﻿using System;
using System.IO;
using System.Net;

namespace Laps.Lib.Core
{
    public class WebStream
    {
        #region Champs
        private FileInfo _fichier;
        #endregion

        #region Méthodes
        public WebStream()
        {
        }
        public void Save(string url)
        {
            HttpWebRequest webRequestObject;
            WebResponse response;
            Stream webStream;
            Uri uri;
            string sfilename;

            uri = new Uri(url);

            sfilename = Path.GetFileName(uri.LocalPath);
            _fichier = new FileInfo(Path.Combine("Temp", sfilename));
            if (_fichier.Exists == true)
            {
                _fichier.Delete();
            }

            using (StreamWriter sw = new StreamWriter(_fichier.FullName))
            {
                // Open a connection
                webRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);
                // You can also specify additional header values like 
                // the user agent or the referer:
                webRequestObject.UserAgent = "Laps";
                // Request response:
                response = webRequestObject.GetResponse();
                // Open data stream:
                webStream = response.GetResponseStream();
                using (StreamReader sr = new StreamReader(webStream))
                {

                    sw.Write(sr.ReadToEnd());
                }
                sw.Close();
            }

        }
        #endregion

        #region Propriétés
        public string FileName
        {
            get
            {
                string sresult = "";
                if (_fichier != null)
                {
                    sresult = _fichier.FullName;
                }
                return sresult;
            }
        }
        #endregion

    }
}
